// ==UserScript==
// @name           Vanilla new discussions in tabs
// @namespace      http://ngo.org.uk/nik/
// @description    Adds a link to open all discussions with new comments in tabs.
// @include        http://forum.stillwater-rock.com/
// ==/UserScript==


/**
 * Return a list of URLs to discussions that have new comments.
 */
function getDiscussionLinks() {
    var r = document.evaluate("//li[contains(concat(' ', normalize-space(@class), ' '), ' NewComments ')]/ul/li[@class='DiscussionTopic']/a", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);

    if (! r.snapshotLength) {
        return;
    } else {
        var hrefs = [];
        for (var i = 0, l = r.snapshotLength; i < l; i++) {
            hrefs[i] = r.snapshotItem(i).href;
        }

        return hrefs;
    }
}

/**
 * Create a link to open all of them in new tabs, and place this just after
 * the first h1 in the Content div.  If clicked, find all the links to
 * discussions with new comments, and open each one in a new tab.
 */
function main() {
    var div_content = document.getElementById('Content');
    var h1 = div_content.getElementsByTagName('h1')[0];

    var p = document.createElement('p');
    var a = document.createElement('a');
    p.appendChild(a);

    a.addEventListener('click', function(event) {
        var hrefs = getDiscussionLinks();
        for (var i = 0, l = hrefs.length; i < l; i++) {
            //GM_log('Would open ' + hrefs[i]);
            GM_openInTab(hrefs[i]);
        }
        return false;
    }, true);

    a.innerHTML = 'Open discussions with new comments in tabs';

    h1.parentNode.insertBefore(p, h1.nextSibling);
}

main();